﻿using System;
using System.Collections.Generic;
using System.Linq;
using ZX.Common;
using ZX.DBModule;
using ZX.EHR.Library;
using System.Data;

using ZX.RuleEngine.Core;
using OpenExpressApp.DB.Utils;

namespace ZX.BLL.Extend
{
    /// <summary>
    /// BllBase 的摘要说明。
    /// </summary>
    public  class BaseBussnies
    {
        public BaseBussnies(BaseEntity entitys)
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
            entity = entitys;
            
        }

        public BaseEntity entity
        {
            get;
            set;
        }

        public BaseBussnies CreateBussniess(string entityName)
        {
            return BaseBussnies.CreateInstance(entityName);
        }

        public BaseBussnies CreateBussniess()
        {
            return BaseBussnies.CreateInstance(this.entity.GetType().Name);
        }


        public BaseBussnies(string entity)
        {
            DataTableBaseEntity _entity = new DataTableBaseEntity();
            _entity.TableName = entity;
            _entity.CreateDT();
            //_entity.SetConn(entity);
            this.entity = _entity;
        }

        public BaseBussnies() { }

        /// <summary>
        /// 新增实体数据
        /// </summary>
        /// <param name="entitys">实体</param>
        public virtual bool Insert(object entitys)
        {
            ZX.SPL.Factory.DialectFactory DF = ZX.SPL.Factory.Dialects.GetDialect(entitys);
            return DF.Save();
        }

        public virtual bool Insert(object entitys, out string msg)
        {
            msg = "";
            try
            {
                return Insert(entitys);
            }
            catch (Exception e)
            {
                msg = e.Message;
                return false;
            }
        }

        
        /// <summary>
        /// 新增实体数据
        /// </summary>
        public virtual  bool Insert()
        {
            return Insert(entity);
        }

        public virtual bool Insert(out string msg)
        {
            return Insert(entity, out msg);
        }
        /// <summary>
        /// 更新实体数据
        /// </summary>
        /// <param name="entitys">实体</param>
        public virtual bool Update(object entitys)
        {
            ZX.SPL.Factory.DialectFactory DF = ZX.SPL.Factory.Dialects.GetDialect(entitys);
            return DF.Update();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="entitys"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public virtual bool Update(object entitys, out string msg)
        {
            msg = "";
            try
            {
                return Update(entitys);
            }
            catch (Exception e)
            {
                msg = e.Message;
                return false;
            }
        }


        /// <summary>
        /// 更新实体数据
        /// </summary>
        public virtual bool Update()
        {
            return Update(entity);
        }

        public virtual bool Update(out string msg)
        {
            return Update(entity,out msg);
        }



        /// <summary>
        /// 删除实体的数据
        /// </summary>
        /// <param name="entitys">实体</param>
        public virtual bool delete(object entitys)
        {
            ZX.SPL.Factory.DialectFactory DF = ZX.SPL.Factory.Dialects.GetDialect(entitys);
            return DF.Delete();
        }

        public virtual bool delete(object entitys,out string msg)
        {
            msg = "";
            try
            {
                return delete(entitys);
            }
            catch (Exception e)
            {
                msg = e.Message;
                return false;
            }
        }
        /// <summary>
        /// 删除实体的数据
        /// </summary>
        public virtual bool delete()
        {
            return delete(entity);
        }

        public virtual bool delete(string condition)
        {
            ZX.SPL.Factory.DialectFactory DF = ZX.SPL.Factory.Dialects.GetDialect(entity);
            return DF.Delete(condition);
        }
        /// <summary>
        /// 通过ID获取实体
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <returns>实体</returns>
        public virtual  BaseEntity GetEntityById(string id)
        {
            if (id == "" || id == null)
            {
                return null;
            }
            else
            {
                try
                {
                    ZX.SPL.Factory.DialectFactory df = ZX.SPL.Factory.Dialects.GetDialect(this.entity);
                    string _strSel = df.SelectCommand(id);
                    return GetEntityBySqlComm(_strSel) as BaseEntity;
                }
                catch
                {
                    return null;
                }
            }
        }


        //public virtual DataTableBaseEntity GetDTEntityByID(string id,string TableName)
        //{
        //    if (id == "" || id == null)
        //    {
        //        return null;
        //    }
        //    else
        //    {
        //        try
        //        {
        //            ZX.SPL.Factory.DialectFactory df = ZX.SPL.Factory.Dialects.GetDialect(this.entity);
        //            string _strSel = df.SelectCommand(id);
        //            return GetEntityBySqlComm(_strSel) as BaseEntity;
        //        }
        //        catch
        //        {
        //            return null;
        //        }
        //    }
        //}

        /// <summary>
        /// 根据不同实体实例化业务实例
        /// 用于实现的不同的实体调用不同的业务逻辑
        /// </summary>
        /// <param name="entityName"></param>
        /// <returns></returns>
        public static BaseBussnies CreateInstance(string entityName)
        {
            DBModule.Entity entity = (new BaseBussnies()).GetEntityByCondition<DBModule.Entity>("entityName='" + entityName + "'");
            if (entity != null)
            {
                if (entity.BLLConfig != null)
                {
                    try
                    {
                        string[] str = entity.BLLConfig.Split(',');
                        return Common.Reflection.CreateInstance(str[0], str[1]) as BaseBussnies;
                    }
                    catch { }
                }
            }
            return new BaseBussnies();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual T GetEntityById<T>(int id)
        {
            BaseEntity be = default(T) as BaseEntity;
            return GetEntityByCondition<T>(be.GetTableId() + "=" + id);
        }




        /// <summary>
        /// 获取需要自动保存的字段列表
        /// </summary>
        /// <param name="tableName">表名或者实体名</param>
        /// <returns></returns>
        public IList<EditUIConfig> GetSysAutoSaveFieldList(string tableName)
        {
            return GetEntitys<EditUIConfig>("EntityName='" + tableName + "' and IsSysAutoSave='Y'");
        }
        /// <summary>
        /// 通过SqlComm命令获取实体
        /// </summary>
        /// <param name="SqlComm">Sql Command</param>
        /// <returns>实体</returns>
        public virtual object GetEntityBySqlComm(string SqlComm)
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return null;
            }
            else
            {
                try
                {
                    ZX.SPL.ORM.ObjectMapper om = new ZX.SPL.ORM.ObjectMapper(entity);
                    om.SqlComm = SqlComm;
                    return om.DataTableToObject();
                }
                catch
                {
                    return null;
                }
            }
        }
        //public virtual T GetEntityById<T>(Guid id)
        //{
        //    return default(T);
        //}

        public virtual T GetEntityById<T>(Guid id)
        {
            BaseEntity be = Activator.CreateInstance<T>() as BaseEntity;
            return GetEntityByCondition<T>(be.GetTableId() + "='" + id.ToString() + "'");
        }

        public virtual T GetEntityBySqlComm<T>(string SqlComm)
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return default(T);
            }
            else
            {
                try
                {
                    object o;
                    o = System.Activator.CreateInstance<T>();
                    //if (this.entity is DataTableBaseEntity)
                    //{
                    //    o = System.Activator.CreateInstance<T>() as BaseEntity;
                    //}
                    //else
                    //{
                    //    o = this.entity;
                    //}
                    ZX.SPL.ORM.ObjectMapper om = new ZX.SPL.ORM.ObjectMapper(o,SqlComm);
                    om.SqlComm = SqlComm;
                    return (T)om.DataTableToObject();
                }
                catch
                {
                    return default(T);
                }
            }
        }


        public virtual string GetRoleCondition(DatUser User,string EntityName, Guid functionID)
        {
            IList<ZX.EHR.Library.SysRoleFunction> list = (new ZX.BLL.BUser()).GetRoleFunction(User.UserID, functionID);
            System.Text.StringBuilder strCondition = new System.Text.StringBuilder("");

            if (list == null)
            {
                return "";
            }
            int i = 0;
            foreach (var entity in list)
            {
                switch (entity.OperateRangeType.Trim())
                {
                    ///只能查看本人数据
                    case "0":
                        i++;
                        if (i < 2)
                        {
                            if (strCondition.ToString() != "")
                            {
                                strCondition.Append(" OR ");
                            }

                            if (EntityName == "V_HF_TaskInstanceClassView")
                            {

                                strCondition.Append("select distinct * from V_HF_TaskInstanceClassView where opercontent in ");
                                strCondition.Append(string.Format("(select 'All' as  OperContent union all select OperContent from HF_opercontentView where  UserId='{0}') and TaskTypeId <> '1'", User.LoginName));
                                strCondition.Append(" union   select distinct VF.* from V_HF_TaskInstanceClassView VF left join HF_opercontentView HF ");
                                strCondition.Append(" on VF.OperContent = HF.operContent inner join HF_AccreditUser AF on ");
                                strCondition.Append(" HF.UserId = AF.AccreditFromUserId and VF.WorkFlowId = AF.WorkFlowId");
                                strCondition.Append(" and VF.taskStartTime >= AF.AccreditDateTime and (Status = '1' or Status ='2') ");
                                strCondition.Append(string.Format(" and AccreditToUserId = '{0}' and AccreditStatus = '1'", User.LoginName));

                            }
                            else if (EntityName == "V_HF_ClaimedWorkTask")
                            {
                                strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                            }
                            else if (EntityName == "V_HF_CompleteWorkTask")
                            {
                                strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                            }
                            else if (EntityName == "V_HF_MyAllWorkTask")
                            {
                                strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                            }
                            else if (EntityName == "V_HF_AbnormalTask")
                            {
                                strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                            }
                            else if (EntityName == "HF_WorkFlowInstanceView")
                            {
                                strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                            }
                            else if (EntityName == "WorkFlowInstanceClassView")
                            {
                                strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                            }
                            else if (EntityName == "WorkTaskCompleteClassView")
                            {
                                strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                            }
                            else if (EntityName == "WorkTaskInstanceClassView")
                            {
                                strCondition.Append(string.Format(" W.UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                            }
                            else if (EntityName == "HF_WorkFlowApplicationClassView")
                            {
                                strCondition.Append(string.Format(" W.UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                            }
                            else if (EntityName == "HF_WorkFlowApproveClassView")
                            {
                                // strCondition.Append(string.Format(" OperContent in (select OperContent from HF_opercontentView where UserId='{0}')", CSVHelper.FmSQL(User.LoginName)));
                                strCondition.Append(string.Format(" W.UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                            }
                            else if (EntityName == "HF_ErrorLogsClassView")
                            {
                                strCondition.Append(string.Format(" OperContent in (select OperContent from HF_opercontentView where UserId='{0}')", CSVHelper.FmSQL(User.LoginName)));
                               // strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                            }
                            else if (EntityName == "HF_WorkTaskInstanceCloseView")
                            {
                                strCondition.Append(string.Format(" W.UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                            }
                            else
                            {
                                strCondition.Append(string.Format(" AddUser='{0}'", User.UserID));
                            }
                        }
                        break;
                    ///可以看本部门的
                    case "1":
                        if (strCondition.ToString() != "")
                        {
                            strCondition.Append(" OR ");
                        }

                        if (EntityName == "V_CrmCustomerShow")
                        {
                            //strCondition.Append(string.Format(" AreaId in  (select  VALUE  from  fn_Split((select DEPTIDS  from dbo.V_UserEmp  where userid='{0}'),',')) and IsPrevate=0 and IsValue=1", User.UserID));    
                            strCondition.Append(string.Format(" AreaId in  (select DeptID from V_CrmUserArea where UserID='" + User.UserID + "') and IsPrevate='0' and IsValue='1'", User.UserID));
                        }
                        else if (EntityName == "V_CrmCustomerInfo")
                        {

                        }
                        else if (EntityName == "WorkFlowInstanceClassView")
                        {
                            strCondition.Append(string.Format("UserId in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", User.UserID));
                        }
                        else if (EntityName == "WorkTaskCompleteClassView")
                        {
                            strCondition.Append(string.Format("UserId in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", User.UserID));
                        }
                        else if (EntityName == "WorkTaskInstanceClassView")
                        {
                            strCondition.Append(string.Format("UserId in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", User.UserID));
                        }
                        else if (EntityName == "HF_WorkFlowApplicationClassView")
                        {
                            strCondition.Append(string.Format("UserId in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", User.UserID));
                        }
                        else if (EntityName == "HF_WorkFlowApproveClassView")
                        {
                            strCondition.Append(string.Format("UserId in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", User.UserID));
                        }
                        else if (EntityName == "HF_ErrorLogsClassView")
                        {
                            strCondition.Append(string.Format("UserId in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", User.UserID));
                        }
                        else if (EntityName == "HF_WorkTaskInstanceCloseView")
                        {
                            strCondition.Append(string.Format("UserId in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", User.UserID));
                        }
                        else
                        {
                            strCondition.Append(string.Format("AddUser in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", User.UserID));
                        }
                        break;
                    // 全部数据
                    case "2":
                        if (strCondition.ToString() != "")
                        {
                            strCondition.Append(" OR ");
                        }
                        strCondition.Append("1=1");
                        if (EntityName == "V_HF_TaskInstanceClassView")
                            return string.IsNullOrEmpty(strCondition.ToString()) ? "" : "(" + strCondition.ToString() + ")";
                        break;
                    //自定义部门条件
                    case "3":
                        // 如果自定义条件
                        if (strCondition.ToString() != "")
                        {
                            strCondition.Append(" OR ");
                        }
                        if (EntityName == "WorkFlowInstanceClassView")
                        {
                            strCondition.Append(string.Format("UserId in (select UserID from dbo.fn_GetDeptsUsers('{0}'))", entity.Depts));
                        }
                        else if (EntityName == "WorkTaskCompleteClassView")
                        {
                            strCondition.Append(string.Format("UserId in (select UserID from dbo.fn_GetDeptsUsers('{0}'))", entity.Depts));
                        }
                        else if (EntityName == "WorkTaskInstanceClassView")
                        {
                            strCondition.Append(string.Format("UserId in (select UserID from dbo.fn_GetDeptsUsers('{0}'))", entity.Depts));
                        }
                        else if (EntityName == "HF_WorkFlowApplicationClassView")
                        {
                            strCondition.Append(string.Format("UserId in (select UserID from dbo.fn_GetDeptsUsers('{0}'))", entity.Depts));
                        }
                        else if (EntityName == "HF_WorkFlowApproveClassView")
                        {
                            strCondition.Append(string.Format("UserId in (select UserID from dbo.fn_GetDeptsUsers('{0}'))", entity.Depts));
                        }
                        else if (EntityName == "HF_ErrorLogsClassView")
                        {
                            strCondition.Append(string.Format("UserId in (select UserID from dbo.fn_GetDeptsUsers('{0}'))", entity.Depts));
                        }
                        else if (EntityName == "HF_WorkTaskInstanceCloseView")
                        {
                            strCondition.Append(string.Format("UserId in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", User.UserID));
                        }
                        else
                        {
                            strCondition.Append(string.Format("AddUser in (select UserID from dbo.fn_GetDeptsUsers('{0}'))", entity.Depts));
                        }
                        break;
                    // 自定义条件数据
                    case "4":
                        if (strCondition.ToString() != "")
                        {
                            strCondition.Append(" OR ");
                        }
                        if (entity.Condition != string.Empty)
                        {
                            strCondition.Append(" " + entity.Condition + " ");
                        }
                        break;
                    default:
                        break;
                }
            }

            //只用客户用户时使用
            if (User.IsOutsite == true)
            {
                if (EntityName == "TrActivity")
                {
                    if (strCondition.ToString() != "")
                    {
                        strCondition.Append(" OR ");
                    }

                    strCondition.Append(string.Format("(TrCustomerID='{0}')", User.CustomerID));

                }
                if (EntityName == "V_TrActivityCourse")
                {
                    if (strCondition.ToString() != "")
                    {
                        strCondition.Append(" OR ");
                    }
                    strCondition.Append(string.Format("(TrCustomerID = '{0}')", User.CustomerID));
                }
            }
            return string.IsNullOrEmpty(strCondition.ToString()) ? "" : strCondition.ToString();// +"," + list[0].OperateRangeType.Trim();
        }

        /// <summary>
        /// 获取插入更新的Sql Command
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public virtual string GetSqlCommand(BaseEntity entity)
        {
            ZX.SPL.Factory.DialectFactory DF = ZX.SPL.Factory.Dialects.GetDialect(entity);
            return DF.GetSqlCommand();
        }

        /// <summary>
        /// 通过SqlComm命令获取实体
        /// </summary>
        /// <param name="SqlComm">Sql Command</param>
        /// <returns>实体</returns>
        public virtual IList<BaseEntity> GetEntitysBySqlComm(string SqlComm)
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return null;
            }
            else
            {
                try
                {
                    SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + iTop.ToString()) : SqlComm;
                    string order = this.Order == "" || this.Order == null ? "" : " Order by " + this.Order;
                    //order = order == "" ? " " : order + (this.Desc == "Yes" ? "  Desc " : " Asc");
                    ZX.SPL.ORM.ObjectMapper om = new ZX.SPL.ORM.ObjectMapper(entity);

                    om.SqlComm = SqlComm + " " + order;
                    return om.DatatableToObject();
                }
                catch (System.Exception ex)
                {
                    return null;
                }
            }
        }
        public virtual IList<T> GetEntitysBySqlComm<T>(string SqlComm)
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return null;
            }
            else
            {
                try
                {
                    SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + iTop.ToString()) : SqlComm;
                    string order = this.Order == "" || this.Order == null ? "" : " Order by " + this.Order;
                    //order = order == "" ? " " : order + (this.Desc == "Yes" ? " Desc " : " Asc");
                    ZX.SPL.ORM.TObject<T> om = new ZX.SPL.ORM.TObject<T>(SqlComm);
                    om.SqlComm = SqlComm + " " + order;
                    return om.DatatableToObject<T>();
                }
                catch (System.Exception ex)
                {
                    return null;
                }
            }
        }


        public IList<TableInfoStruc> GetTableInfoStruc(string tableName)
        {
            return this.GetEntitysBySqlComm<TableInfoStruc>("select * from V_TableInfoStruc where +TableName='" + tableName + "'");
        }

        public string GetTableKey(string tableName)
        {
            var o = this.GetEntitysBySqlComm<TableInfoStruc>("select * from V_TableInfoStruc where TableName='" + tableName + "' and Substring(PKey,1,1)='Y'");
            if (o == null)
            {
                if (tableName.IndexOf('.') > 0)
                {
                    return this.GetEntitys<DataListTemplate>("EntityName='" + tableName.Split('.')[1] + "'").First().Field;
                }
                else
                {
                    return this.GetEntitys<DataListTemplate>("EntityName='" + tableName + "'").First().Field;
                }
            }
            return (o == null) ? "ID" : o.First().ColName;

        }

        public virtual System.Data.DataTable GetDTByTable(string tableName)
        {
            ZX.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(null);
            return om.GetDataTableByTableName(tableName);
            //ZX.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
            //return om.GetDataBySqlComm();
        }

        public virtual System.Data.DataTable GetDataBySqlComm(string SqlComm)
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return null;
            }
            else
            {
                try
                {
                    ZX.SPL.ORM.ObjectMapper om = new ZX.SPL.ORM.ObjectMapper(entity);
                    om.SqlComm = SqlComm;
                    return om.GetDataBySqlComm();
                }
                catch
                {
                    return null;
                }
            }
        }

        public virtual System.Data.DataTable GetDTStuceByTable(string tableName)
        {
            ZX.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(null);
            return om.GetDTStrucByTableName(tableName);
        }


        public virtual IList<BaseEntity> GetEntitysSplitPage(string Condition)
        {
            this.Order = (this.Order == "" ? this.entity.getKey() : this.Order);
            string SqlComm = string.Empty;
            try
            {
                //2012-11-16：15：33添加RowNumber排序
                string order = string.IsNullOrEmpty(this.Order) ? "" : "( Order by " + this.Order +" ) ";
                //order = string.IsNullOrEmpty(order) ? " " : order + (this.Desc == "Yes" ? " Desc) " : " Asc) ");
                SqlComm = "SELECT TOP " + PageSize.ToString() + " * FROM  (  SELECT ROW_NUMBER() OVER" + order + " AS RowNumber,* FROM " + this.entity.getTableName() + (string.IsNullOrEmpty(Condition) ? "" : " where " + Condition) + ") A WHERE RowNumber > " + (PageIndex - 1) * PageSize + " order by RowNumber";
                //SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + PageSize.ToString()) : SqlComm;
                ZX.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
                om.SqlComm = SqlComm;
                return om.DatatableToObject();
            }
            catch (System.Exception ex)
            {
                return null;
            }

        }
        
        public virtual IList<BaseEntity> GetEntitysByCondition(string Condition)
        {
            ZX.SPL.Factory.DialectFactory df = ZX.SPL.Factory.Dialects.GetDialect(entity);
            return GetEntitysBySqlComm(df.SelectAllCommand() + " where " + Condition);
        }

        public System.Data.DataTable CreateDataTable(string tableName)
        {
            IList<TableInfoStruc> tfList = GetTableInfoStruc(tableName);
            System.Data.DataTable dt = new System.Data.DataTable();
            foreach (TableInfoStruc tifs in tfList)
            {
                dt.Columns.Add(tifs.TableName, ZX.Common.Globals.CovertDBType(tifs.CType));
            }
            return dt;
        }

        public System.Data.DataTable CreateDataTable(string tableName,out IList<TableInfoStruc> tf)
        {
            IList<TableInfoStruc> tfList = GetTableInfoStruc(tableName);
            System.Data.DataTable dt = new System.Data.DataTable();
            foreach (TableInfoStruc tifs in tfList)
            {
                dt.Columns.Add(tifs.ColName, ZX.Common.Globals.CovertDBType(tifs.CType));
            }
            tf = tfList;
            return dt;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="Json"></param>
        /// <returns></returns>
        public virtual System.Data.DataTable GetSingleRowDT(string tableName, string Json)
        {
            Dictionary<string, object> JsonData = ZX.Common.Globals.ConvertToDictionary(Json);
            IList<TableInfoStruc> tf;
            System.Data.DataTable dt = CreateDataTable(tableName,out tf);
            System.Data.DataRow dr = dt.NewRow();
            foreach (KeyValuePair<string, object> field in JsonData)
            {
                string FType = tf.Where(p => p.ColName == field.Key).Select(p => p.CType).FirstOrDefault();
                dr[field.Key] = ZX.Common.Globals.CovertValue(FType,field.Value as string);
            }
            dt.Rows.Add(dr);
            return dt;
            //object[] rows =      (object[])JsonData["row"];
            //foreach (object ob in rows)
            //{
            //    Dictionary<string, object> val = (Dictionary<string, object>)ob;
            //    DataRow dr = gsr.RetrunData.NewRow();
            //    foreach (KeyValuePair<string, object> sss in val)
            //    {
            //        //dr[sss.Key] = sss.Value;
            //    }
            //    //gsr.RetrunData.Rows.Add(dr);
            //}
            //return gsr;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public virtual IList<BaseEntity> GetEntitys()
        {
            ZX.SPL.Factory.DialectFactory df = ZX.SPL.Factory.Dialects.GetDialect(this.entity);
            return this.GetEntitysBySqlComm(df.SelectAllCommand());
        }
        public virtual IList<T> GetEntitys<T>()
        {
            ZX.SPL.Factory.DialectFactory df = ZX.SPL.Factory.DialectFactory.instance<T>();
            return this.GetEntitysBySqlComm<T>(df.SelectAllCommand());
        }
        //public IList<T> GetEntitys<T>()
        //{
        //    ZX.SPL.Factory.DialectFactory df = ZX.SPL.Factory.Dialects.GetDialect(this.entity);
        //    return this.GetEntitysBySqlComm(df.SelectAllCommand());
        //}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Condition"></param>
        /// <returns></returns>
        public virtual IList<BaseEntity> GetEntitys(string Condition)
        {
            if (Condition == null || Condition == string.Empty)
            {
                return GetEntitys();
            }
            else
            {
                ZX.SPL.Factory.DialectFactory df = ZX.SPL.Factory.Dialects.GetDialect(entity);
                IList<BaseEntity> entitys= this.GetEntitysBySqlComm(df.SelectAllCommand() + " where " + Condition);
                return entitys;
            }
        }
        public virtual IList<T> GetEntitys<T>(string Condition)
        {
            if (Condition == null || Condition == string.Empty)
            {
                return GetEntitys<T>();
            }
            else
            {
                ZX.SPL.Factory.DialectFactory df = ZX.SPL.Factory.DialectFactory.instance<T>();
                return this.GetEntitysBySqlComm<T>(df.SelectAllCommand() + " where " + Condition);
            }
        }
        /// <summary>
        /// 生成XML文件
        /// </summary>
        /// <param name="SqlComm"></param>
        /// <returns></returns>
        public virtual string BuildXmlFile(string SqlComm)
        {
            ZX.SPL.ORM.ObjectMapper om = new ZX.SPL.ORM.ObjectMapper(new object(), SqlComm);
            return om.BuildXmlFile();
        }
        /// <summary>
        /// 数据实体数组
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual IList<BaseEntity> GetEntitysByIds(string[] id)
        {
            if (id.Length == 0)
            {
                return null;
            }

            IList<BaseEntity> al = new List<BaseEntity>();
            for (int i = 0; i < id.Length - 1; i++)
            {
                BaseEntity obj = GetEntityById(id[i]);
                al.Add(obj);
            }
            return al;
        }
        //public IList<T> GetEntitysByIds<T>(string[] id)
        //{
        //    if (id.Length == 0)
        //    {
        //        return null;
        //    }

        //    ArrayList al = new ArrayList();
        //    for (int i = 0; i < id.Length - 1; i++)
        //    {
        //        object obj = GetEntityById(id[i]);
        //        al.Add(obj);
        //    }
        //    return al.ToArray();
        //}
        /// <summary>
        /// 通过条件获取实体
        /// </summary>
        /// <param name="Condition">条件</param>
        /// <returns>实体</returns>
        public virtual object GetEntityByCondition(string Condition)
        {
            ZX.SPL.Factory.DialectFactory df = ZX.SPL.Factory.Dialects.GetDialect(entity);
            return this.GetEntityBySqlComm(df.SelectAllCommand() + " where " + Condition);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Condition"></param>
        /// <returns></returns>
        public virtual T GetEntityByCondition<T>(string Condition)
        {
            ZX.SPL.Factory.DialectFactory df = ZX.SPL.Factory.DialectFactory.instance<T>();
            return this.GetEntityBySqlComm<T>(df.SelectAllCommand() + " where " + Condition);
        }
       
        [Obsolete("不要再override此方法了",false)]
        public virtual string CheckData(BaseEntity entity)
        {
            if (entity == null)
            {
                return CheckData();
            }
            string msg = RunScript(entity, null);
            if (string.IsNullOrEmpty(msg))
            {
                return CheckData();
            }
            return msg;
        }

        /// <summary>
        /// 数据检查，用于页面调用自定义
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public virtual string CheckData(BaseEntity entity,object page)
        {

            string msg="";
            try
            {
                msg = RunScript(entity, page);
            }
            catch { return msg; }
            return msg;
        }


        public string RunScript(BaseEntity entity,object page)
        {
            Entity _entity = null;
            if (entity is DataTableBaseEntity)
            {
                _entity = this.GetEntityByCondition<Entity>("EntityName='" + this.entity.GetTableName() + "'");
            }
            else
            {
                _entity = this.GetEntityByCondition<Entity>("EntityName='" + this.entity.GetType().Name + "'");
            }

            if (_entity == null)
                return "";
            if (string.IsNullOrEmpty(_entity.RoleScript))
                return "";
            string _script = @"msg='';
                               function check(e){
                                    {0}
                                   }
                               func = check;
                               msg = func(entity);
                               ".Replace("{0}",_entity.RoleScript).Replace("[B]","'");
            string msg = RoleRuntimeHost.CheckData(this.entity, _script,page);
            return msg;
          }

        public virtual string CheckData() 
        { 
            return ""; 
        }

        public virtual string EditCheckData()
        {
            return "";
        }

        public virtual string DeleteCheckData()
        {
            return "";
        }

        /// <summary>
        /// 通过规则配制文件
        /// </summary>
        /// <returns>信息</returns>
        //public string CheckInfo()
        //{
        //    string config = this.entity.GetType().ToString();
        //    config = config.Replace("ZX.DBModule.","");
        //    config = config + ".iSun.Xml";
        //    config = ConfigurationSettings.AppSettings["webroot"] + "RoleConfig\\" + config ;
        //    //config = ConfigurationSettings.AppSettings["ConfigPath"] + config ;
        //    StringBuilder msg = new StringBuilder("");
        //    XmlControls xctrl = new XmlControls(config);
        //    if ( xctrl == null )
        //    {
        //        return "";
        //    }

        //    XmlNode node = xctrl.GetNode("UI-mapping/class");
        //    foreach(XmlNode xnode in node.ChildNodes)
        //    {
        //        if (xnode.Attributes["PermissionNull"].Value == "0")
        //        {
        //            object obj = iSun.Common.ReflectionUntil.GetPropertyValue(this.entity,xnode.Attributes["name"].Value);
        //            if ( obj == null || isEmpty(obj,xnode.Attributes["type"].Value))
        //            {
        //                msg.Append(xnode.Attributes["name"].Value+"]不能为空!\n");
        //            }
        //        }
        //    }
        //    return msg.ToString();
        //}


        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="DataType"></param>
        /// <returns></returns>
        public bool isEmpty(object obj, string DataType)
        {
            if (obj == null)
            {
                return true;
            }

            if (DataType.IndexOf("String") == 0)
            {
                if ((string)obj == string.Empty)
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 获取唯一标识符
        /// </summary>
        /// <returns></returns>
        public string GetGuids()
        {
            if (this.entity is DataTableBaseEntity)
            {
                DataTableBaseEntity table = ((DataTableBaseEntity)this.entity);
                if(!string.IsNullOrEmpty(((DataTableBaseEntity)this.entity).TableKey))
                {
                    return table.TableKey;
                }
                else
                {
                    TableInfoStruc entity = this.GetEntityByCondition<TableInfoStruc>("TableName='"+table.TableName+"' and Substring(PKey,1,1)='Y'");
                    if (entity == null)
                    {
                        this.Order = "iOrder";
                        this.Desc = "No";
                        return this.GetEntitys<DataListTemplate>("EntityName='" + table.TableName + "'").First().Field;
                    }
                    return entity.ColName;
                }
            }
            else
            {
                Type t = this.entity.GetType();
                foreach (Attribute attr in t.GetCustomAttributes(true))
                {
                    ZX.DBModule.TableAttribute tableattribute = attr as ZX.DBModule.TableAttribute;
                    if (null != tableattribute)
                    {
                        return tableattribute.Guid;
                    }
                }
                return "";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public string[] GetKey()
        {
            return this.GetKey(this.entity.getTableName());
        }

        public string[] GetKey(string tableName)
        {
            string[] str = new string[2];
            TableInfoStruc entity = this.GetEntityByCondition<TableInfoStruc>("TableName='" + tableName + "' and Substring(PKey,1,1)='Y'");
            if (entity != null)
            {
                str[0] = entity.ColName;
                str[1] = entity.CType;
            }
            return str;
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <returns></returns>
        public virtual IList<BaseEntity> GetEntitysSplitPage()
        {
                string SqlComm=string.Empty;
                try
                {
                    string order = this.Order == "" || this.Order == null ? "" : "( Order by " + this.Order +" ) ";
                    order = order == "" ? " " : order + (this.Desc == "Yes" ? " Desc) " : " Asc) ");
                    SqlComm = "SELECT TOP "+PageSize.ToString()+" * FROM  (   SELECT ROW_NUMBER() OVER"+this.Order+" AS RowNumber,* FROM " +this.entity.getTableName()+ ") A WHERE RowNumber > "+(PageIndex-1)*PageSize;
                    //SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + PageSize.ToString()) : SqlComm;
                    ZX.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
                    om.SqlComm = SqlComm;
                    return om.DatatableToObject();
                }
                catch (System.Exception ex)
                {
                    return null;
                }
        }

        //public virtual System.Data.DataTable GetEntitysSplitPage()
        //{
        //    string SqlComm = string.Empty;
        //    try
        //    {
        //        string order = this.Order == "" || this.Order == null ? "" : "( Order by " + this.Order;
        //        order = order == "" ? " " : order + (this.Desc == "Yes" ? " Desc) " : " Asc) ");
        //        SqlComm = "SELECT TOP " + PageSize.ToString() + " * FROM  (   SELECT ROW_NUMBER() OVER" + this.Order + " AS RowNumber,* FROM " + this.entity.getTableName() + ") A WHERE RowNumber > " + (PageIndex - 1) * PageSize;
        //        //SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + PageSize.ToString()) : SqlComm;
        //        ZX.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
        //        om.SqlComm = SqlComm;
        //        return om.);
        //    }
        //    catch (System.Exception ex)
        //    {
        //        return null;
        //    }
        //}

        /// <summary>
        /// 执行 Sql Command
        /// </summary>
        /// <param name="SqlCommand"></param>
        /// <returns></returns>
        public int RunSqlCommand(string SqlCommand)
        {
            return (new ZX.DAL.DBExtend.DbSql()).ExecuteSqlTran(SqlCommand);
        }

        public DataTable GetDeptandDuty(string empid)
        {
            BUser buser=new BUser();
            return buser.GetDeptandDuty(empid);
        }
        /// <summary>
        /// 执行 Sql Command
        /// </summary>
        /// <param name="SqlCommand"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public int RunSqlCommand(string SqlCommand, out string msg)
        {
            msg = "";
            try
            {
                return RunSqlCommand(SqlCommand);
            }
            catch(Exception e)
            {
                msg = "信息源:"+e.Source+"/r/n消息:"+e.Message;
                return -1;
            }
        }

        public DataSet RunProcedure(string storedProcName, IDataParameter[] parameters)
        {
            return (new ZX.DAL.DBExtend.DbSql()).RunProcedure(storedProcName, parameters,true);

        }



        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storeProcName">存储过程</param>
        /// <param name="para">参数</param>
        /// <returns></returns>
        public lite.IResultSet RunProcedure(string storeProcName, object[] para)
        {
            lite.IResultSet _set = null;
            using (var db = DBHelper.CreateDb(ZX.DAL.ConnectionStringNames.OpenExpressApp))
            {
                _set = db.Exec(storeProcName, para);
            }
            return _set;
        }

        #region 相关属性
        public virtual int iTop
        {
            get;
            set;
        }

        public virtual string Order
        {
            get;
            set;
        }

        public virtual string Desc
        {
            get;
            set;
        }

        public virtual int PageIndex
        {
            get;
            set;
        }

        public virtual int PageSize
        {
            get;
            set;
        }
        #endregion

    }
}